package xyz.zhzby.cyzx.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import xyz.zhzby.cyzx.acl.convert.RoleConvert;
import xyz.zhzby.cyzx.acl.dto.response.RoleResponse;
import xyz.zhzby.cyzx.acl.service.IRolePermissionService;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.DataLogInfo;
import xyz.zhzby.cyzx.servicebase.utils.StringUtils;
import xyz.zhzby.cyzx.acl.dto.request.RolePageRequest;
import xyz.zhzby.cyzx.acl.entity.Role;
import xyz.zhzby.cyzx.acl.entity.UserRole;
import xyz.zhzby.cyzx.acl.mapper.RoleMapper;
import xyz.zhzby.cyzx.acl.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.acl.service.IUserRoleService;
import xyz.zhzby.cyzx.servicebase.domain.PageResponse;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    //根据用户获取角色数据
    @Override
    public RestResponse<Map<String, Object>> findRoleByUserId(Long userId) {
        //查询所有的角色
        List<Role> allRolesList = baseMapper.selectList(null);

        //根据用户id，查询用户拥有的角色id
        LambdaQueryWrapper<UserRole> qw = new LambdaQueryWrapper<>();
        qw.eq(UserRole::getUserId, userId);
        qw.select(UserRole::getRoleId);
        List<UserRole> existUserRoleList = userRoleService.list(qw);

        List<Long> existRoleList = existUserRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());

        //对角色进行分类
        List<Role> assignRoles = new ArrayList<Role>();
        for (Role role : allRolesList) {
            //已分配
            if (existRoleList.contains(role.getId())) {
                assignRoles.add(role);
            }
        }

        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assignRoles", assignRoles);
        roleMap.put("allRolesList", allRolesList);
        return RestResponse.success(roleMap);
    }

    //根据用户分配角色
    @Override
    public void saveUserRoleRealtionShip(Long userId, Long[] roleIds) {
        LambdaQueryWrapper<UserRole> qw = new LambdaQueryWrapper<>();
        qw.eq(UserRole::getUserId, userId);
        userRoleService.remove(qw);

        List<UserRole> userRoleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);

            userRoleList.add(userRole);
        }
        userRoleService.saveBatch(userRoleList);
    }

    @Override
    public List<Role> selectRoleByUserId(Long id) {
        //根据用户id拥有的角色id
        LambdaQueryWrapper<UserRole> qw = new LambdaQueryWrapper<>();
        qw.eq(UserRole::getUserId, id);
        qw.select(UserRole::getRoleId);
        List<UserRole> userRoleList = userRoleService.list(qw);
        List<Long> roleIdList = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Role> roleList = new ArrayList<>();
        if (roleIdList.size() > 0) {
            roleList = baseMapper.selectBatchIds(roleIdList);
        }
        return roleList;
    }

    @Override
    public RestResponse<PageResponse<RoleResponse>> queryRoles(RolePageRequest pageRequest) {
        Page<Role> page = new Page<>(pageRequest.getPage(), pageRequest.getLimit());
        LambdaQueryWrapper<Role> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotNullOrBlank(pageRequest.getName())) {
            qw.like(Role::getName, pageRequest.getName());
        }
        qw.orderByAsc(Role::getId);
        IPage<Role> pagedata = baseMapper.selectPage(page, qw);
        List<Role> records = pagedata.getRecords();
        List<RoleResponse> list = RoleConvert.INSTANCE.ROLE_RESPONSE_LIST(records);
        return RestResponse.success(new PageResponse<>(list, pagedata.getTotal(), pageRequest.getPage(), pageRequest.getLimit()));
    }

    @Override
    public RestResponse<String> saveRole(Role role) {
        User subject = CyzxSecurityContextHolder.getSubject();
        subject.fillCreateInfo(role, DataLogInfo.USER_FIELD_ACTUAL_NAME);
        baseMapper.insert(role);
        return RestResponse.success("添加成功");
    }

    @Override
    public RestResponse<RoleResponse> getOneById(Long roleId) {
        return RestResponse.success(RoleConvert.INSTANCE.ROLE_RESPONSE(baseMapper.selectById(roleId)));
    }

    @Override
    public RestResponse<String> updateOne(Role role) {
        CyzxSecurityContextHolder.getSubject().fillUpdateInfo(role, DataLogInfo.USER_FIELD_ACTUAL_NAME);
        baseMapper.updateById(role);
        return RestResponse.success("修改成功");
    }

    @Override
    public RestResponse<String> removeRole(Long roleId) {
        rolePermissionService.removeByRoleId(roleId);
        userRoleService.removeByRoleId(roleId);
        baseMapper.deleteById(roleId);
        return RestResponse.success("移除成功");
    }

    @Override
    public RestResponse<String> removeRoleBatch(List<Long> ids) {
        ids.forEach(this::removeRole);
        return RestResponse.success("移除成功");
    }
}
